var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tc: 1,
    util: util,

    showAuthView: false,

    userinfo: {},
    cuid: 0,
    token: '',
    openid: '',

    guiGoodsInfo: '',

    totalPrice: 0,
    colorSet: '',

    content_w: 318,
    item_min_w: 60,
    item_max_w: 120,
    item_min_h: 80,
    item_max_h: 160,

    indicatorDots: true,
    autoplay: true,
    interval: 4000,
    duration: 600,
    startTime: 0,
    swiper_w: 320,
    swiper_h: 160,
    swiperImgUrls: '',

    verifyShow: false
  },

  wxAuthFail: true,
  guiId: '',
  guiIsOnline: true,
  orgInfo: '',

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    this.guiId = options.guiid ? options.guiid : '';

    var tc = app.get_tc();
    var that = this;

    wx.getSystemInfo({
      success: function(res) {
        var min_w = (res.windowWidth - 30) / 5;
        var max_w = (res.windowWidth - 20) / 3;
        var min_h = min_w * 1.25;
        that.setData({
          content_w: res.windowWidth,
          item_min_w: min_w,
          item_max_w: max_w,
          item_min_h: min_w + 25,
          item_max_h: max_w + 25,
          swiper_w: res.windowWidth,
          swiper_h: res.windowWidth / 3,
        })
      },
    })

    this.getPassWords();

    app.GetUserInfo(util.orgid, function(res) {
      console.log("绑定小程序信息：", res);
      that.orgInfo = res;
    });
    //获取颜色配置
    app.getColorSetData(function(color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    if (this.guiId) {
      this.getGuiInfo();
    } else {
      wx.showModal({
        title: '提示',
        content: '未能获取售货机ID，请检查小程序码是否正确',
        showCancel: false
      })
    }
    this.showAuthView(false, false);
    this.loadSwiperImage();
  },


  userCancelAuth: function() { //用户取消授权
    this.hiddenAuthView();
    wx.navigateBack({
      delta: 1
    })
  },
  showAuthView: function(showCancel, reAuth) {
    var that = this;
    wx.getSetting({
      success: (res) => {
        console.log("已授权列表：", res);
        var authStatus_userInfo = res.authSetting["scope.userInfo"];
        if (authStatus_userInfo) {
          that.getLoginUserInfo();
        } else {
          var authToastOb = {};
          authToastOb.showCancel = showCancel;
          authToastOb.msg = that.orgInfo.uname + " 需要您的授权"
          that.setData({
            showAuthView: true,
            authToastData: authToastOb
          })
        }
      }
    });
  },
  hiddenAuthView: function() {
    this.setData({
      showAuthView: false
    })
  },
  loginUserInfo: function(res) {
    if (res.detail.encryptedData) { //如果包含有这个字段，说明用户授权了
      this.getLoginUserInfo();
    }
  },

  getLoginUserInfo: function() {
    var that = this;
    wx.showLoading({
      title: 'loading...',
      mask: 'true'
    });
    //读取登录用户信息
    app.LoginUserInfo(function(res) {
      if (res && res != -1) {
        that.wxAuthFail = false;
        //更新数据
        that.setData({
          cuid: res.uid,
          openid: res.wxsmall_openid,
          token: res.token
        })
      } else {
        that.wxAuthFail = true;
      }
      wx.hideLoading();
    }, '');
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  submitFormId: function(e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      var navPath = path.slice(6);
      wx.navigateTo({
        url: navPath,
      })
    } else {
      wx.redirectTo({
        url: path
      });
    }
  },

  liuyanInput: function(e) {
    console.log("留言：" + e.detail.value);
    this.setData({
      liuyan: e.detail.value
    });
  },

  //获取柜子的商品信息
  getGuiInfo: function() {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getguiinfo",
        "guiid": that.guiId
      },
      success: function(responseData) {
        console.log("柜子的商品信息：", responseData);
        var guiInfo = responseData.data;
        var noticeText = '';
        if (!guiInfo.isalive) {
          noticeText = '此自动售货机连接异常，请检查电源和网络是否正常';
          guiInfo.err_msg = noticeText;
        }

        that.guiIsOnline = true;
        var titlename = guiInfo.title ? guiInfo.title : '自助售货机';
        let start = guiInfo.guiid.length - 4;
        guiInfo.showguiid = "ID: ******" + guiInfo.guiid.substr(start, 4)
        if (guiInfo.roomid) {
          guiInfo.showguiid = "ID: ******" + guiInfo.guiid.substr(start, 4) + "。 房号: " + guiInfo.roomid;
        }
        wx.setNavigationBarTitle({
          title: titlename,
        })
        that.setData({
          guiGoodsInfo: guiInfo
        });

        if (!guiInfo.isalive) {
          that.guiIsOnline = false;
          wx.showModal({
            title: '温馨提示',
            content: noticeText,
            showCancel: false
          });

        }
      }
    });
  },

  //打开所有缺货的舱门
  openAll:function(){
    let boxIds = '';
    for(let i = 1; i <= 10; i++){
      let key = "box" + i;
      if(this.data.guiGoodsInfo[key].isfull == 0){
        if (boxIds) {
          boxIds += (',' + i);
        } else {
          boxIds = '' + i;
        }
      }
    }
    if (boxIds) {
      console.log("舱门id组：" + boxIds);
      this.openGuiBox(boxIds, false);
    } else {
      wx.showModal({
        title:"提示",
        content:"此售货机为满货状态，如是误点“一键补货”，请联系管理员"
      })
    }
  },
  //设置所有缺货状态的格子为有货
  setAllHasGoods: function () {
    let boxIds = '';
    for (let i = 1; i <= 10; i++) {
      let key = "box" + i;
      if (this.data.guiGoodsInfo[key].isfull == 0) {
        if(boxIds){
          boxIds += (',' + i);
        } else {
          boxIds = ''+i;
        }
      }
    }
    if(boxIds){
      console.log("舱门id组：" + boxIds);
      this.setBoxFull(boxIds);
    }
  },

  selBoxId: 0,
  selBoxData: '',
  addGoodsAction: function(e) {
    if (!this.guiIsOnline) {
      wx.showModal({
        title: '温馨提示',
        content: '此自动售货机连接异常，请检查电源和网络是否正常',
        showCancel: false
      });
      return;
    }
    this.selBoxId = 0;
    this.selBoxData = '';
    var boxId = e.currentTarget.dataset.boxid;
    var boxData = e.currentTarget.dataset.boxdata;
    if (boxData.isfull == '1') {
      var that = this;
      if (this.data.userinfo.verified == '1' && this.data.userinfo.catatype == '8'){
        let notice = '系统显示这个格子有货，确定要打开舱门吗？';
        wx.showModal({
          title: '提示',
          content: notice,
          showCancel: false,
          confirmText: "打开舱门",
          success: function (res) {
            if (res.confirm) {
              that.openGuiBox(boxId, true);
            }
          }
        })
      } else {
        let notice = '系统显示这个格子有货，如需更换请联系管理人员';
        wx.showModal({
          title: '提示',
          content: notice,
          showCancel: false
        })
      }
    } else {
      this.openGuiBox(boxId, true);
    }

  },

  passwords: '',
  getPassWords: function() {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getManagePassword",
      },
      success: function(responseData) {
        console.log("管理密码信息：", responseData.data);
        that.passwords = responseData.data;
      }
    });
  },

  regetPassword: function() {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '验证码数据获取失败',
      showCancel: false,
      confirmText: '重新获取',
      success: function(res) {
        if (res.confirm) {
          that.getPassWords();
        }
      }
    })
  },

  hideVerify: function() {
    this.setData({
      verifyShow: false
    });
  },
  verifySubmit: function(e) {
    if (this.passwords && this.passwords.guanpwd) {
      var url = e.currentTarget.dataset.url;
      if (e.detail.value.pwd == this.passwords.guanpwd) {
        this.hideVerify();
        this.openGuiBox(this.selBoxId, true);
      } else if (e.detail.value.pwd == '') {
        wx.showToast({
          icon: "none",
          title: this.data.tc == 1 ? '請輸入驗證碼' : '请输入验证码',
        })
      } else {
        wx.showToast({
          icon: "none",
          title: '验证码错误',
        })
      }
    } else {
      this.regetPassword();
    }

  },

  //添加商品
  openGuiBox: function(boxId, isBuhuo) {
    wx.showLoading({
      title: 'loading...',
    });

    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'openguibox' + that.data.token);
    var data = {
      'ac': "openguibox",
      'uid': that.data.cuid,
      'privatekey': privatekey,
      'guiid': that.guiId,
      'boxid': boxId
    };
    console.log("打开格子门", data);

    util.api({
      data: data,
      method: 'POST',
      success: function(responseData) {
        wx.hideLoading();
        var data = responseData.data;
        console.log("打开格子门返回：", data);
        if (data.res) {
          if(isBuhuo){
            wx.showModal({
              title: '提示',
              content: '如已放置货物，请选择“已补货”；如舱门未弹开，请选“开门”',
              confirmText: "已补货",
              cancelText: "开门",
              success: function (res) {
                if (res.confirm) {
                  that.setBoxFull(boxId);
                } else {
                  that.openGuiBox(boxId, isBuhuo);
                }
              }
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: '打开舱门失败',
            confirmText: "重试",
            success: function(res) {
              if (res.confirm) {
                that.openGuiBox(boxId, isBuhuo);
              }
            }
          })
        }
      }
    });
  },

  setBoxFull: function(boxId) {
    //设置这个格子有货物了
    wx.showLoading({
      title: 'loading...',
    });
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'setguibox' + that.data.token);
    var data = {
      'ac': "setguibox",
      'uid': that.data.cuid,
      'privatekey': privatekey,
      'guiid': that.guiId,
      'boxid': boxId,
      'setval': 1
    };
    console.log("设为有货：", data);

    util.api({
      data: data,
      method: 'POST',
      success: function(responseData) {
        wx.hideLoading();
        var data = responseData.data;
        console.log("设为有货返回：", data);
        if (data.res) {
          wx.showToast({
            title: '补货成功',
          })
          that.getGuiInfo();
        } else {
          wx.showModal({
            title: '提示',
            content: '系统添加货物失败',
            confirmText: "重试",
            success: function(res) {
              if (res.confirm) {
                that.setBoxFull(boxId);
              }
            }
          })
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    // this.getAddress();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },



  resetNavColor: function() {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  //index 001  幻灯片数据
  loadSwiperImage: function() {
    var that = this;
    var params = {
      "publickey": util.publiccode,
      "ac": "indexslide",
      "uid": util.orgid,
      "block": 1,
      "tc": '',
    };
    util.api({
      data: params,
      success: function(responseData) {
        console.log("-- swiper image:", responseData);
        var result = responseData.data;
        if (result && result.length > 0) {
          //轮播图
          that.setData({
            swiperImgUrls: result
          });
        }
        wx.hideLoading();
      }
    });
  },

  //时间戳转换时间  
  toDate: function(number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    console.log(Y + M + D + "  " + H + ':' + m)
    return (Y + M + D + "  " + H + ':' + m)

  },

})